package unique;

//import backup.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FileHandler {

    public FileHandler(String file) {
        fileName = file;
        createFile();
        loadFile();
    }

    public void createFile() {
        try {
            archive = new File(fileName);
            if (archive.createNewFile()) {
                System.out.println("[Server] File " + fileName + " created.");
            } else {
                System.out.println("[Server] File " + fileName + " already exists.");
            }
        } catch (IOException ex) {
            Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void resetList() {
        cardsList = new LinkedList<Model>();
    }

    /* Name of the archive */
    //private final String fileName = "archive.txt";
    String fileName;
    File archive;

    /* Collection of cards */
    private LinkedList<Model> cardsList;

    /* Draft variables */
    private String line;
    private int tempID = 0;

    public void loadFile() {
        try {
            resetList();
            line = "";

            BufferedReader br = new BufferedReader(new FileReader(archive));

            while ((line = br.readLine()) != null) {
                loadLine();
                //               System.out.println(line);
            }

            br.close();
        } catch (IOException ex) {
            Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void loadLine() {
        String[] tempAtt = line.split(" : ");
        Model tempModel = new Model();

        tempModel.setId(Integer.parseInt(tempAtt[0]));
        tempModel.setName(tempAtt[1]);
        tempModel.setType(tempAtt[2]);
        tempModel.setMana(tempAtt[3]);
        tempModel.setSet(tempAtt[4]);
        tempModel.setConvMana(Integer.parseInt(tempAtt[5]));
        tempModel.setPower(Integer.parseInt(tempAtt[6]));
        tempModel.setTough(Integer.parseInt(tempAtt[7]));
        tempModel.setRarity(tempAtt[8]);
        //tempModel.setFlavor(tempAtt[9].split(" ::: ")[1]);
        tempModel.setFlavor(tempAtt[9]);
        tempModel.setAmmount(Integer.parseInt(tempAtt[10]));

        cardsList.add(tempModel);
    }

    public void addCard(String newModel) {
        String[] tempAtt = newModel.split(" : ");
        Model tempModel = new Model();

        tempModel.setId(Integer.parseInt(tempAtt[0]));
        tempModel.setName(tempAtt[1]);
        tempModel.setType(tempAtt[2]);
        tempModel.setMana(tempAtt[3]);
        tempModel.setSet(tempAtt[4]);
        tempModel.setConvMana(Integer.parseInt(tempAtt[5]));
        tempModel.setPower(Integer.parseInt(tempAtt[6]));
        tempModel.setTough(Integer.parseInt(tempAtt[7]));
        tempModel.setRarity(tempAtt[8]);
        //tempModel.setFlavor(tempAtt[9].split(" ::: ")[1]);
        tempModel.setFlavor(tempAtt[9]);
        tempModel.setAmmount(Integer.parseInt(tempAtt[10]));

        if (getCardById(tempModel.getId()) == null) {
            addToFile(tempModel);
        } else {
            tempModel.increaseAmmount();
            removeFromFile(tempModel.getId());
            addToFile(tempModel);
        }
    }

    public void addToFile(Model newCard) {
        try {
            cardsList.add(newCard);
            BufferedWriter bw = new BufferedWriter(new FileWriter(archive, true));
            bw.write(newCard.toString() + "\n");
            bw.flush();
        } catch (IOException ex) {
            System.err.println("Error 0x01: Trouble during reading of the file.");
        }
    }

    public Model getCardById(int id) {
        for (int i = 0; i < cardsList.size(); i++) {
            if (cardsList.get(i).getId() == id) {
                return cardsList.get(i);
            }
        }

        return null;
    }
    
    public Model getCardByIdLL (int id) {
        return cardsList.get(id);
    }

    public Model getNextCard() {
        System.out.println(tempID);
        if (tempID++ < cardsList.size()) {
            System.out.println("getnext: " + cardsList.get((tempID - 1)));
            return cardsList.get((tempID - 1));
        }
        // tomar cuidado aqui, pode dar pau
        return null;
    }

    public void resetNextCard() {
        tempID = 0;
    }

    public Model getCardByName(String name) {
        for (int i = 0; i < cardsList.size(); i++) {
            if (cardsList.get(i).getName().equals(name)) {
                return cardsList.get(i);
            }
        }

        return null;
    }

    public LinkedList<Model> getCardByCost(int cost) {
        LinkedList<Model> manaCards = new LinkedList<Model>();

        for (int i = 0; i < cardsList.size(); i++) {
            if (cardsList.get(i).getConvMana() == cost) {
                manaCards.add(cardsList.get(i));
            }
        }

        return manaCards;
    }

    public void removeCardById(int id) {
        for (int i = 0; i < cardsList.size(); i++) {
            if (cardsList.get(i).getId() == id) {
                cardsList.remove(i);
                removeFromFile(id);
            }
        }//*/
//        System.out.println("so motherfucking deep");
//        cardsList.remove(id);
    }

    public void resetFile() {
        archive.delete();
        File newF = new File("tempArchive.tmp");
        try {
            newF.createNewFile();
        } catch (IOException ex) {
            Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        newF.renameTo(archive);
    }
    
    public void removeFromFile(int id) {
        BufferedWriter writer = null;
        try {
            cardsList.remove(getCardById(id));
            File tempFile = new File("temp.txt");
            BufferedReader reader = new BufferedReader(new FileReader(archive));
            writer = new BufferedWriter(new FileWriter(tempFile));
            String temp;
            while ((temp = reader.readLine()) != null) {
                if (temp.split(" : ")[0].equals("" + id)) {
                    continue;
                }
                writer.write(temp + System.getProperty("line.separator"));
            }
            writer.close();
            reader.close();
            tempFile.renameTo(archive);
        } catch (IOException ex) {
            Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                writer.close();
            } catch (IOException ex) {
                Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void editCardById(int id, String flavor) {
        for (int i = 0; i < cardsList.size(); i++) {
            if (cardsList.get(i).getId() == id) {
                cardsList.get(i).setFlavor(flavor);
            }
        }
    }

    public void testPrint() {
        for (int i = 0; i < cardsList.size(); i++) {
            System.out.println(cardsList.get(i).toString());
        }
    }

    public LinkedList<Model> getCardsList() {
        return cardsList;
    }

    public void setCardsList(LinkedList<Model> cardsList) {
        this.cardsList = cardsList;
    }

}
